package k8s_ui

import (
	"context"
	"errors"
	"github.com/wonderivan/logger"
	"k8s.io/api/core/v1"
	storage "k8s.io/api/storage/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

var StorageClasses storageclasses

type storageclasses struct {
	K8s *kubernetes.Clientset
}

// StorageClass 结构体
type StorageClass struct {
	Name                 string
	Provisioner          string
	ReclaimPolicy        *v1.PersistentVolumeReclaimPolicy
	VolumeBindingMode    *storage.VolumeBindingMode
	AllowVolumeExpansion *bool
}

func (s *storageclasses) GetStorageClasses() (data []StorageClass, err error) {
	// List StorageClasses
	storageClasses, err := K8s.ClientSet.StorageV1().StorageClasses().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		logger.Error(errors.New("查询StorageClasses失败, " + err.Error()))
		return data, err
	}

	//添加返回列表
	for _, sc := range storageClasses.Items {

		//自定义判断是否支持扩容
		var allowExpansion bool
		if sc.AllowVolumeExpansion != nil {
			allowExpansion = *sc.AllowVolumeExpansion
		} else {
			allowExpansion = false
		}

		data = append(data, StorageClass{
			Name:                 sc.Name,
			Provisioner:          sc.Provisioner,
			ReclaimPolicy:        sc.ReclaimPolicy,
			VolumeBindingMode:    sc.VolumeBindingMode,
			AllowVolumeExpansion: &allowExpansion,
		})
	}
	return data, nil
}

//func (s *storageclasses) CreateStorageClasses(storageclassname string, provisioner string) (data []StorageClass, err error) {
//	storageClass2 := &storage.StorageClass{
//		ObjectMeta: metav1.ObjectMeta{
//			Name: storageclassname,
//		},
//		Provisioner: provisioner,
//		Parameters: map[string]string{
//			"type": "gp2",
//		},
//	}
//
//	// Create the StorageClass
//	result, err := K8s.ClientSet.StorageV1().StorageClasses().Create(context.TODO(), storageClass2, metav1.CreateOptions{})
//	if err != nil {
//		panic(err.Error())
//	}
//	fmt.Printf("Created StorageClass %q.\n", result.GetObjectMeta().GetName())
//
//	return data, nil
//}
